package org.jdragon.springz.web.core.configuration;

import lombok.Getter;
import org.jdragon.springz.core.utils.InjectedUtils;
import org.jdragon.springz.web.core.entity.HttpRequest;
import org.jdragon.springz.web.core.entity.HttpResponse;
import org.jdragon.springz.web.core.handler.WebHandler;

import java.util.List;
import java.util.ListIterator;

/**
 * @Author JDragon
 * @Date 2021.03.03 下午 3:50
 * @Email 1061917196@qq.com
 * @Des:
 */

@Getter
public class WebFilterChain {

    private WebHandler webHandler;

    private List<WebFilter> webFilters;

    private ListIterator<WebFilter> iterator;

    private WebFilter currentFilter;

    private WebFilterChain chain;

    public static WebFilterChain initChain(WebHandler webHandler) {
        List<WebFilter> webFilters = InjectedUtils.getBeanWithClass(WebFilter.class);
        WebFilterChain chain = new WebFilterChain(webHandler, webFilters);
        ListIterator<WebFilter> webFilterListIterator = webFilters.listIterator();
        if (webFilterListIterator.hasNext()) {
            chain = new WebFilterChain(webHandler, webFilters, chain);
        }
        return chain;
    }


    private WebFilterChain(WebHandler webHandler, List<WebFilter> filters) {
        this.webHandler = webHandler;
        this.webFilters = filters;
    }

    private WebFilterChain(WebHandler webHandler, List<WebFilter> filters, WebFilterChain chain) {
        this.webHandler = webHandler;
        this.webFilters = filters;
        this.iterator = filters.listIterator();
        this.currentFilter = iterator.next();
        this.chain = chain;
    }

    public void filter(HttpRequest httpRequest, HttpResponse httpResponse) {
        if (chain != null && currentFilter != null) {
            currentFilter.filter(httpRequest, httpResponse, chain);
            currentFilter = iterator.hasNext() ? iterator.next() : null;
        } else {
            webHandler.handle(httpRequest, httpResponse);
        }
    }
}
